package top.kaoshanji.p1ch11a;

import org.apache.hc.core5.http.ContentType;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 代码清单-p1ch11a-378页a：包含若干目录项
 * URL访问地址：/nileBooks
 * @author kaoshanji
 * ^_^
 * create time 2025/4/5 16:08
 */
public class NileBooks extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        // 设置响应对象的编码和内容格式
        resp.setContentType(ContentType.TEXT_HTML.toString());
        PrintWriter out = resp.getWriter();

        out.println("<HTML><HEAD><TITLE>Welcome to Nile</TITLE></HEAD>");
        out.println("<BODY>");

        out.println("Feast your eyes on this beauty:");
        req.setAttribute("item", Book.getBook("0596000405"));

        // 从在线目录显示项目
        RequestDispatcher dispatcher = req.getRequestDispatcher("/nileItem");
        dispatcher.include(req, resp); // 将 "/nileItem" 内容插入到此处..场景一：没有找到书

        // 用后删除 “item” 属性
        req.removeAttribute("item");
        out.println("Or how about this one:");
        req.setAttribute("item", Book.getBook("0395282659"));
        dispatcher.include(req, resp); // 将 "/nileItem" 内容插入到此处..场景二：找到书

        out.println("And, since I like you, they're all 20% off!");

        out.println("</BODY></HTML>");
    }

}
